import { delDevice, getDeviceList } from '@/services/api/device';
import { getDeviceTypeList } from '@/services/api/deviceType';
import { DeviceParams } from '@/services/api/model/deviceModel';
import { ActionType, PageContainer, ProList } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import {
  Avatar,
  Badge,
  Button,
  Card,
  Divider,
  Image,
  Popconfirm,
  Space,
  Tag,
  theme,
  Typography,
} from 'antd';
import React, { useRef } from 'react';
import AssignmentsForm from './components/AssignmentsForm';
import CreateForm from './components/CreateForm';
const DevicePage: React.FC = () => {
  const { Paragraph } = Typography;
  const { useToken } = theme;
  const onCancel = () => {};
  const actionRef = useRef<ActionType>();
  // 删除
  const handleConfirm = async (id: string) => {
    try {
      await delDevice(id);
      actionRef.current!.reloadAndRest!();
      Promise.resolve(null);
    } catch {
      Promise.resolve(null);
    }

    // 这里 return 一个 primise 之后会执行异步关闭 resolve(null) 之后关闭
    // return new Promise(async (resolve) => {
    //   try {
    //     await delDevice(id);
    //     actionRef.current!.reloadAndRest!();
    //     resolve(null);
    //   } catch (error) {
    //     resolve(null);
    //   }
    // });
  };

  //提交
  const onSubmit = () => {
    // 重置到默认值，包括表单
    // 断言标识,reloadAndRest一定是存在的
    actionRef.current!.reloadAndRest!();
  };
  const { token } = useToken();
  return (
    <PageContainer>
      <Card bodyStyle={{ padding: '10px' }}>
        <ProList<DeviceParams>
          actionRef={actionRef}
          toolbar={{
            // 新建
            actions: [
              <CreateForm key={102938} onCancel={onCancel} onSubmit={onSubmit}></CreateForm>,
            ],
          }}
          request={async (
            // 第一个参数 params 查询表单和 params 参数的结合
            // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
            params: DeviceParams & {
              deviceTypeSearch?: string[];
            },
          ) => {
            // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
            // 如果需要转化参数可以在这里进行修改
            const msg = await getDeviceList({
              // 这里传入数组之后,默认会有序列化的
              deviceTypeList: params.deviceTypeSearch,
              deviceName: params.name,
              deviceToken: params.token,
              page: params.current,
              pageSize: params.pageSize,
              includeVoiceBox: true,
              includeDeviceType: true,
              includeAssignment: true,
              excludeAssigned: false,
            });
            return {
              data: msg.results.map((m) => {
                // 是否存在分配
                const isAssign =
                  m.idevice &&
                  m.idevice.activeDeviceAssignments &&
                  m.idevice.activeDeviceAssignments.length;
                return {
                  ...m,
                  ...m.idevice,
                  ...{
                    ...m.user,
                    userURL: IMG_URL + m.user?.url,
                  },
                  imageUrl: IMG_URL + m.idevice?.deviceType?.imageUrl,
                  voiceBoxUrl:
                    isAssign && IMG_URL + m.idevice.activeDeviceAssignments[0]?.voiceBox?.imageUrl,
                  areaUrl:
                    isAssign && IMG_URL + m.idevice.activeDeviceAssignments[0]?.area?.imageUrl,
                  aassetUrl:
                    isAssign && IMG_URL + m.idevice.activeDeviceAssignments[0]?.asset?.imageUrl,
                };
              }),
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: msg.numResults,
            };
          }}
          pagination={{
            defaultPageSize: 20,
            showSizeChanger: false,
          }}
          showActions="always"
          rowSelection={{}}
          grid={{ gutter: 16, column: 3 }}
          onItem={(record: any) => {
            return {
              onMouseEnter: () => {
                // console.log(record);
              },
              onClick: () => {
                console.log(record);
                history.push('/deviceAdmin/Device/DeviceDetails');
              },
            };
          }}
          search={{
            span: 6,
            // filterType: 'light',
            // searchGutter: 2,
            // 搜索表单的样式
            style: {
              padding: 0,
            },
          }}
          metas={{
            // time: {
            //   // colSize: 1.2,
            //   // 自己扩展的字段，主要用于筛选，不在列表中显示
            //   title: '日期',
            //   valueType: 'dateRange',
            //   // T00:00:00.000+08:00 2019-01-25T00:00:00-02:00Z
            //   fieldProps: {
            //     format: 'YYYY-MM-DDTHH:mm:ss.SSSZ',
            //   },

            //   // initialValue: Date.now(),
            // },

            avatar: {
              render: (_, row, index) => {
                return (
                  <div
                    key={index}
                    style={{
                      width: 48,
                      height: 48,
                      lineHeight: '22px',
                      backgroundSize: '100%',
                      textAlign: 'center',
                      padding: '8px 16px 16px 12px',
                      color: '#FFF',
                      fontWeight: 'bold',
                      display: 'inline-block',
                      backgroundImage:
                        "url('https://gw.alipayobjects.com/zos/bmw-prod/daaf8d50-8e6d-4251-905d-676a24ddfa12.svg')",
                    }}
                  >
                    {index + 1}
                  </div>
                  // <Avatar
                  //   src={'https://gw.alipayobjects.com/zos/antfincdn/UCSiy1j6jx/xingzhuang.svg'}
                  // />
                );
              },
              search: false,
            },

            actions: {
              // 操作栏 处于的位置 ,extra 顶部 actions 底部
              cardActionProps: 'extra',
              // 注意:所有的数组格式的 都要添加一个key
              render: (_, row) => [
                <Space key={11123123}>
                  {/* 添加分配 */}
                  <AssignmentsForm
                    deviceToken={row.token!}
                    onSubmit={() => actionRef.current!.reloadAndRest!()}
                  ></AssignmentsForm>
                  <Divider key={'divider1'} type="vertical" />
                  <Popconfirm
                    onOpenChange={() => console.log('open change')}
                    key={'del12'}
                    title="确定删除吗"
                    onConfirm={() => handleConfirm(row.token!)}
                  >
                    <Button key={'del1'} danger style={{ width: '100%' }} size="small">
                      删除
                    </Button>
                  </Popconfirm>
                </Space>,
              ],
              search: false,
            },
            subTitle: { search: false },
            type: { search: false },
            content: {
              search: false,
              render: (_, row) => {
                return (
                  <div style={{ width: '100%' }}>
                    <div style={{ display: 'flex' }}>
                      <Image
                        width={90}
                        height={90}
                        src={row.imageUrl}
                        fallback=""
                      />
                      <div
                        style={{
                          marginLeft: '10px',
                        }}
                      >
                        <div style={{ display: 'flex' }}>
                          设备类型:
                          <Paragraph copyable={{ tooltips: false }}>
                            {row.deviceType?.name}
                          </Paragraph>{' '}
                        </div>
                        <div style={{ display: 'flex' }}>
                          Token:
                          <Paragraph copyable={{ tooltips: false }}>{row?.token}</Paragraph>{' '}
                        </div>
                        <div style={{ display: 'flex' }}>
                          描述:
                          <Paragraph copyable={{ tooltips: false }}>{row?.comments}</Paragraph>{' '}
                        </div>
                      </div>
                    </div>
                    <Divider
                      style={{
                        color: '#999',
                      }}
                    >
                      分配
                    </Divider>
                    <div style={{ width: '100%' }}>
                      <Space
                        size={16}
                        align="baseline"
                        style={{
                          width: '100%',
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'center',
                        }}
                      >
                        <Badge
                          size="small"
                          status="processing"
                          count={'用户'}
                          color={token.colorPrimaryBorder}
                        >
                          <Avatar shape="square" size={40} src={row.userURL} />
                        </Badge>
                        <Badge
                          size="small"
                          status="processing"
                          count={'音箱'}
                          color={token.colorPrimaryBorder}
                        >
                          <Avatar shape="square" size={40} src={row.voiceBoxUrl} />
                        </Badge>

                        <Badge
                          size="small"
                          status="processing"
                          count={'站点'}
                          color={token.colorPrimaryBorder}
                        >
                          <Avatar shape="square" size={40} src={row.areaUrl} />
                        </Badge>
                        <Badge
                          size="small"
                          status="processing"
                          count={'网关'}
                          color={token.colorPrimaryBorder}
                        >
                          <Avatar shape="square" size={40} src={row.aassetUrl} />
                        </Badge>
                      </Space>
                    </div>
                  </div>
                );
              },
            },
            title: {
              title: '设备名称',
              dataIndex: 'name',
              render: (_, row) => {
                return <Tag color="processing">{row.name}</Tag>;
              },
            },
            token: {
              title: 'Token',
              dataIndex: 'token',
            },
            deviceTypeSearch: {
              // 自己扩展的字段，主要用于筛选，不在列表中显示
              title: '设备类型',
              valueType: 'select',
              // fieldPropsi定义组件的默认参数
              fieldProps: {
                mode: 'multiple',
              },
              request: async () => {
                const msg = await getDeviceTypeList();
                const results = msg?.results;
                return results.map((item) => {
                  return {
                    label: item.name,
                    value: item.token,
                  };
                });
              },
            },
          }}
        />
      </Card>
    </PageContainer>
  );
};

export default DevicePage;
